package com.yzcrm.erp.finance.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Aop;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.yzcrm.common.config.paragetter.BasePageRequest;
import com.yzcrm.common.constant.BaseConstant;
import com.yzcrm.erp.admin.service.AdminRoleService;
import com.yzcrm.erp.admin.service.AdminSceneService;
import com.yzcrm.erp.crm.common.CrmEnum;
import com.yzcrm.erp.psi.service.PsiEnterLeaveStockService;
import com.yzcrm.utils.AuthUtil;
import com.yzcrm.utils.BaseUtil;
import com.yzcrm.utils.R;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jiang.xue
 */
public class FinanceBackLogService {

    @Inject
    FinancePurchaseService financePurchaseService;
    @Inject
    AdminSceneService adminSceneService;

    /**
     * 待办事项数量统计
     */
    public R num() {

        Long userId = BaseUtil.getUserId();
        JSONObject jsonObject= Aop.get(AdminRoleService.class).auth(userId);
        List<String> authList= AuthUtil.queryAuth(jsonObject, "");
        Kv kv = new Kv();

        // 52常规备货normalPurchase
        if (authList.contains("finance:normalPurchase:index")){

            Integer checkSalesEnter = Db.queryInt(Db.getSql("finance.backLog.checkPurchaseNum"),userId, CrmEnum.FINANCE_NORMAL_PURCHASE.getType());
            kv.set("normalPurchase",checkSalesEnter);
        }

        // 53项目备货projectPurchase
        if (authList.contains("finance:projectPurchase:index")){

            Integer checkSalesEnter = Db.queryInt(Db.getSql("finance.backLog.checkPurchaseNum"),userId, CrmEnum.FINANCE_PROJECT_PURCHASE.getType());
            kv.set("projectPurchase",checkSalesEnter);
        }

        // 54研发用品devPurchase
        if (authList.contains("finance:devPurchase:index")){
            Integer checkSalesEnter = Db.queryInt(Db.getSql("finance.backLog.checkPurchaseNum"),userId, CrmEnum.FINANCE_DEV_PURCHASE.getType());
            kv.set("devPurchase",checkSalesEnter);
        }

        // 55 其它otherPurchase
        if (authList.contains("finance:otherPurchase:index")){
            Integer checkSalesEnter = Db.queryInt(Db.getSql("finance.backLog.checkPurchaseNum"),userId, CrmEnum.FINANCE_OTHER_PURCHASE.getType());
            kv.set("otherPurchase",checkSalesEnter);
        }

        // 51办公用品officePurchase
        if (authList.contains("finance:officePurchase:index")){
            Integer checkSalesEnter = Db.queryInt(Db.getSql("finance.backLog.checkPurchaseNum"),userId, CrmEnum.FINANCE_OFFICE_PURCHASE.getType());
            kv.set("officePurchase",checkSalesEnter);
        }

        return R.ok().put("data", kv);
    }

    /**
     * 待审核采购
     * @author lg
     */
    public R checkPurchase(BasePageRequest basePageRequest) {
//  basePageRequest.getJsonOjbect():获取分页列表参数
    	JSONObject jsonObject = basePageRequest.getJsonObject();
//    	jsonObject.getInteger()
    	Integer checkType = jsonObject.getInteger("checkType");
        Integer isSub = jsonObject.getInteger("isSub");
//        查询存在审批记录和日志
        StringBuffer stringBuffer = new StringBuffer("select purchase_id from yzcrm_finance_purchase as a inner join yzcrm_admin_examine_record as b on a.examine_record_id = b.record_id left join yzcrm_admin_examine_log as c on b.record_id = c.record_id where c.is_recheck != 1 and ifnull(b.examine_step_id, 1) = ifnull(c.examine_step_id, 1) and");
//        待审核
        if (checkType == 1){
            stringBuffer.append(" a.check_status in (0,3) and c.examine_status in (0,3)");
        }else if (checkType == 2){
            stringBuffer.append(" a.check_status in (1,2)");
        }else {
            return R.error("checkType类型不正确");
        }

        if (isSub == 1){
            stringBuffer.append(" and c.examine_user = ").append(BaseUtil.getUserId());
        }else if (isSub == 2){
            String ids = adminSceneService.getSubUserId(BaseUtil.getUserId(), BaseConstant.AUTH_DATA_RECURSION_NUM).substring(1);
            stringBuffer.append(" and c.examine_user in (").append(ids).append(")");
        }else {
            return R.error("isSub参数不正确");
        }
        Integer page = basePageRequest.getPage();
        Integer limit = basePageRequest.getLimit();
        stringBuffer.append(" limit ").append((page - 1) * limit).append(",").append(limit);
        List<Integer> elsIds = Db.query(stringBuffer.toString());
        if (elsIds.size() == 0){
            return R.ok().put("data",new ArrayList<>());
        }
        JSONObject data = jsonObject.getJSONObject("data")!=null ? jsonObject.getJSONObject("data") : new JSONObject();

        data.fluentPut("backLog",new JSONObject()
                .fluentPut("name","purchase_id")
                .fluentPut("condition","in")
                .fluentPut("value",StrUtil.join(",",elsIds)));
        jsonObject.fluentPut("data",data).fluentPut("search","");
        basePageRequest.setJsonObject(jsonObject);
        return financePurchaseService.getPurchasePageList(basePageRequest);
    }

}
